package com.netty.timeold;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

import com.netty.timeold.model.BaseModel;
import com.netty.timeold.model.PingReq;
import com.sevenchildren.framework.constant.RespStatus;
import com.sevenchildren.framework.entity.BaseResp;
import com.sevenchildren.framework.entity.BiStringEntry;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class TimeClientSimpleHandler extends SimpleChannelInboundHandler<String> {

	ConcurrentHashMap<String, BaseModel> map = new ConcurrentHashMap<>();

	String name = "";
	ChannelHandlerContext chctx;

	public TimeClientSimpleHandler(String name) {
		this.name = name;
		System.out.println("------------------");
	}

	public BaseResp req(BaseModel model) {
		if (null == model) {
			return BaseResp.newInstance(RespStatus.PARAMS_VALID_ERROR);
		}
		String json = model.toJson();
		String header = BaseModel.getHeader();
		chctx.writeAndFlush(Unpooled.copiedBuffer(BaseModel.toArray(header, json)));
		synchronized (model) {
			map.put(header, model);
			try {
				System.out.println("mememememememememe");
				model.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				return BaseResp.newInstance(RespStatus.REQ_TIME_OUT);
			}
			System.out.println("yyyyyyyyyyy");
			if (StringUtils.isNotBlank(model.getResp())) {
				return BaseResp.newSuccess().msg(model.getResp());
			}
		}
		return BaseResp.newInstance(RespStatus.REQ_TIME_OUT);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer(BaseModel.toArray("", PingReq.getInterface().toJson())));
		chctx = ctx;
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, String body) throws Exception {
		if (PingReq.isPing(body)) {
			return;
		}
		System.out.println("Now is :" + body);
		BiStringEntry bse = BaseModel.parse(body);
		BaseModel model = map.get(bse.getCode());
		if (null != model) {
			model.setResp(bse.getMsg());
			synchronized (model) {
				model.notifyAll();
			}
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	// 利用写空闲发送心跳检测消息
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent) evt;
			System.out.println(e.state());
			switch (e.state()) {
			case ALL_IDLE:
				ctx.writeAndFlush(Unpooled.copiedBuffer("ping".getBytes(StandardCharsets.UTF_8)));
				break;
			default:
				break;

			}

		}

	}

}
